package com.yunlongn.async.idempotent.filter;

import com.yunlongn.async.config.RetrySchedulerConfig;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.concurrent.TimeUnit;

/**
 * 使用redis实现幂等过滤
 *
 * @author yunlongn
 */
public class RedisIdempotentFilter implements IdempotentFilter {

    private final static String CACHE_KEY = "retry_schedule_id:";

    private static final StringRedisTemplate STRING_REDIS_TEMPLATE = RetrySchedulerConfig.getStringRedisTemplate();

    private String getCacheKey(String id) {
        return CACHE_KEY + id;
    }

    @Override
    public boolean needFilter(String id, TimeUnit timeUnit, int[] periods) {
        int totalTime = 0;
        for (int item : periods) {
            totalTime += item;
        }
        // 锁定指定时间， 跟这次的任务设置的调度总时间一致
        Boolean result = STRING_REDIS_TEMPLATE.opsForValue().setIfAbsent(getCacheKey(id), "LOCK", totalTime, timeUnit);
        return !Boolean.TRUE.equals(result);
    }

    @Override
    public void remove(String id) {
        STRING_REDIS_TEMPLATE.delete(getCacheKey(id));
    }

}
